<?php
namespace App\Http\Controllers\SysAdmin;

use App\Models\Achievement;
use App\Models\Attendance;
use App\Models\Company;
use App\Models\Group;
use App\Models\RewardPunishDetail;
use App\Models\RoleUser;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Input;
use App\Models\User;
use App\Models\CorpInfo;
use App\Models\Feedback;
use App\Models\FeedbackDetail;
use App\Models\UserPerformance;
use App\Models\UserPerformanceMonth;
use DB;
use Log;
use App\Models\RegUser;
use App\Models\Tips;

class UserController extends BaseController
{
    protected $role;


    public function __construct() {
        parent::__construct();
        $this->role = RoleUser::where('user_id',$this->user->id)->where('corpid',$this->corpid)->whereIn('role_id',['9'])->get();
        if(count($this->role) == 0){
            abort(403,'您没有权限访问该页面');
        }
    }
    
    //成员个人信息
    public function getIndex(Request $request)
    {
        $uid = $request->input('userid',0);
        if($uid <=0){
            return 'userid有误';
        }
        $user = User::find($uid);
        if($user->corpid != $this->corpid){
            return '您没有权限查看该用户信息';
        }
        //用户角色
        $role = RoleUser::where('corpid',$this->corpid)->where('user_id',$user->id)->lists('role_id');
        $groups = Group::where('corpid',$this->corpid)->select('group_name','id')->get();
        $groups = $groups->toArray();
        $grouparray = array();
        foreach ($groups as $g){
                $grouparr['title'] = $g['group_name'];
                $grouparr['value'] = $g['id'];
            $grouparray[] = $grouparr;
        }
        //dd($grouparray);
        $grouparray = json_encode($grouparray);
        $rolearray = array('9'=>'总','10'=>'考','11'=>'业','12'=>'奖');
        $gender = array('0'=>'未填写','1'=>'男','2'=>'女');
        $user->role = $role;
        if(!strpos($user->old_corp_no ,"web_") === false){
            $view = 'sysadmin.new-colleague';
        }else{
            if(is_mobile()){
                $view = 'sysadmin.web-new-colleague';
            }else{
                $view = 'pc_sysadmin.web-new-colleague';
            }
        }
        return view($view)
            ->with('gender',$gender)
            ->with('groups',$grouparray)
            ->with('rolearray',$rolearray)
            ->with('user',$user);
    }




    //修改成员信息
    public function postModifyUser(Request $request)
    {
        $result = array(
            'status'        => 'success',
            'msg'           => 'ok',
            'data'          => '',
            'redirectUrl'   => ''
        );
        $uid = $request->input('userid',0);
        $groupid = $request->input('groupid',0);
        $is_leader = $request->input('is_leader',0);
        $gender = $request->input('gender',0);
        $is_sales = $request->input('selectsale',0);
        if($is_sales != 1 && $is_sales != 0){
            $is_sales = 0;
        }

        if( $groupid < 0 || $uid <=0){
            $result['status'] = 'fail';
            $result['msg'] = '组id有误或userid有误';
            return Response::json($result);
        }
        
        $user = User::find($uid);
        if($user->corpid != $this->corpid){
            return '您没有权限修改该用户信息';
        }
        if($is_leader == '1'){
            $leader_user = User::where('corpid',$this->corpid)->where('status','1')->where('group_id',$groupid)->where('is_leader','1')->get();
            foreach ($leader_user as $u){
                $u->is_leader = 0;
                $u->save();
            }
            $user->group_id = $groupid;
            $user->gender = $gender;
            $user->is_leader = 1;
            $user->is_sales = $is_sales;
            //$user->gender = $gender;
            $user->save();
        }else{
            $user->group_id = $groupid;
            $user->gender = $gender;
            $user->is_leader = 0;
            $user->is_sales = $is_sales;
           // $user->gender = $gender;
            $user->save();
        }


        $result['data'] = $user;
        $result['msg'] = '修改用户信息成功';
        return Response::json($result);
    }



    //删除成员
    public function postDelUser(Request $request)
    {
        $result = array(
            'status'        => 'success',
            'msg'           => 'ok',
            'data'          => '',
            'redirectUrl'   => ''
        );
        $uid = $request->input('userid',0);

        if(  $uid <=0){
            $result['status'] = 'fail';
            $result['msg'] = 'userid有误';
            return Response::json($result);
        }

        $user = User::find($uid);
        if($user->corpid != $this->corpid){
            $result['status'] = 'fail';
            $result['msg'] = '您没有权限修改该用户信息';
            return Response::json($result);
        }

        $role = RoleUser::where('corpid',$this->corpid)->where('user_id',$uid)->get();
        foreach ($role as $r){
            if($r->role_id == 9){
                $result['status'] = 'fail';
                $result['msg'] = '请先将系统管理员权限移除';
                return Response::json($result);
            }
            $r->delete();
        }

        $user->delete();

        $result['data'] = $user;
        $result['msg'] = '删除成功';
        return Response::json($result);
    }

    
    //查看个人考评
    public function getPerf(Request $request)
    {
        $uid = $request->input('uid',0);
        if($uid <= 0){
            $uid = $this->user->id;
        }

        //判断是否超时，超时重新计算综合绩效
        $cu_perf = UserPerformance::where('user_id',$uid)->where('corpid',$this->corpid)->first();
        //超过一天则计算strtotime("-1 day",time())
        if(!empty($cu_perf) && $cu_perf->updated_at < date("Y-m-d H:i:s",time()))
        {
            $standard_t = Achievement::where('corpid',$cu_perf->corpid)->where('user_id',$cu_perf->user_id)->sum('standard');
            $score_t = Achievement::where('corpid',$cu_perf->corpid)->where('user_id',$cu_perf->user_id)->sum('score');
            if($standard_t == 0){
                $gg = 0;
            }else{
                $gg =  round($score_t/$standard_t,2)*100;
                $gg = intval($gg);
            }

            $kq_score = Attendance::where('corpid',$cu_perf->corpid)->where('user_id',$cu_perf->user_id)->sum('score');

            $reward = RewardPunishDetail::where('corpid',$cu_perf->corpid)->where('to_user_id',$cu_perf->user_id)->where('is_effective','1')->where('kind','1')->sum('score');
            $punish = RewardPunishDetail::where('corpid',$cu_perf->corpid)->where('to_user_id',$cu_perf->user_id)->where('is_effective','1')->where('kind','2')->sum('score');
            $cu_perf->jiangcheng = $reward + $punish;
            $cu_perf->kaoqin = $kq_score;
            $cu_perf->yeji = $gg;
            $cu_perf->total = $gg + $kq_score+ $reward + $punish;
            $cu_perf->save();


            //每月第一天存入上月数据,粗略
            $last_month = date("Ym",strtotime("-1 month",time()));
            $day = date("d",time());
            if($day == '1'){
                $month_data = UserPerformanceMonth::where('user_id',$uid)->where('corpid',$this->corpid)->where('month',$last_month)->first();
                if(empty($month_data)){
                    $last = new UserPerformanceMonth();
                    $last->month = $last_month;
                    $last->corpid = $cu_perf->corpid;
                    $last->user_id = $uid;
                    $last->kaoqin = $cu_perf->kaoqin;
                    $last->yeji = $cu_perf->yeji;
                    $last->jiangcheng = $cu_perf->jiangcheng;
                    $last->total = $cu_perf->total;
                    $last->save();
                }
            }
        }


        $year = date("Y",time());
        $current_m = date("m",time());
        $perf = UserPerformance::where('corpid',$this->corpid)->where('user_id',$uid)->first();
        $view = 'sysadmin.kaohe.my-evaluation';
        //绩效数据月度
        $months = UserPerformanceMonth::where('corpid',$this->corpid)->where('user_id',$uid)->where('month','like',$year.'%')->get();
        $month_array = array(0,0,0,0,0,0,0,0,0,0,0,0);
        $date_array = array('01'=>0,'02'=>1,'03'=>2,'04'=>3,'05'=>4,'06'=>5,'07'=>6,'08'=>7,'09'=>8,'10'=>9,'11'=>10,'12'=>11);
        foreach ($months as $m){
            $mo= str_replace($year,'',$m->month);
            $index = $date_array[$mo];
            $month_array[$index] = $m->total;
        }
        $month_array[$current_m] = $perf->total;
        $month_array = json_encode($month_array);
        //月度意见
        $opinion = DB::select('select `feedback_id`, avg(`score`) as sc,count(`feedback_id`) as cf, sum(`score`) as ss from kh_feedback_detail where corpid = "'.$this->corpid. '" and   to_user_id = '.$uid.' Group By feedback_id');
        $fdname = Feedback::where('corpid',$this->corpid)->lists('name','id');
        $fdname = $fdname->toArray();
        $total_people = User::where('corpid',$this->corpid)->where('status','1')->count();
        //$return_op = array();
        $return_op_v = array();
        $return_op_n = array();
        foreach ($opinion as $op){
            /*$return_op[] = array(
                'value'=>$op->sc,
                'name'=>$fdname[$op->feedback_id],
            );*/
           // $return_op_v[] = round($op->sc,1);
            if($total_people*12 > $op->cf){
                $return_op_v[] = round(4.0 + ($op->ss - (4.0 * $op->cf)) / ($total_people*12),2);
            }else{
                $return_op_v[] = round($op->sc,1);
            }
            $return_op_n[] = $fdname[$op->feedback_id];
        }
        if(count($return_op_n) == 0){
            $return_op_v = [4.0 , 4.0 , 4.0 , 4.0 , 4.0];
            foreach ($fdname as $fdn){
                $return_op_n[] = $fdn;
            }
            //$return_op_n = ['default','default','default','default','default'];
            $is_origin = 1;
        }else{
            $is_origin = 1;
        }
        //$return_op = json_encode($return_op);
        $return_op_v = json_encode($return_op_v);
        //$return_op_n = json_encode($return_op_n);
        //dd($return_op_v,$return_op_n);

        //新增计算每月实时业绩
        $yearmonth = array('01','02','03','04','05','06','07','08','09','10','11','12');
        $jixiao = array();
        foreach ($yearmonth as $k=>$y){
            $target = Achievement::where('corpid',$this->corpid)->where('user_id',$uid)->where('created_at','like',$year.'-'.$y.'%')->sum('standard');
            $finish = Achievement::where('corpid',$this->corpid)->where('user_id',$uid)->where('created_at','like',$year.'-'.$y.'%')->sum('score');
            if($target == 0){
                $yeji = 0;
            }else{
                $yeji = round( $finish/$target,2)*100;
            }
            $start = strtotime($year.'-'.$y.'-01 00:00:00');
            $end = strtotime($year.'-'.$y.'-01 00:00:00 +1 month');
            $end = $end - 1;//防止小于等于重复计算
            $kaoqin = Attendance::where('corpid',$this->corpid)->where('user_id',$uid)->whereBetween('time',[$start,$end])->sum('score');
            $jiangcheng = RewardPunishDetail::where('corpid',$this->corpid)->where('to_user_id',$uid)->where('is_effective','1')->where('effective_month','=',$year.$y)->sum('score');
            $jixiao[] = $yeji + $jiangcheng + $kaoqin;

        }
        $jixiao =  json_encode($jixiao);



        $ac_id=$uid;
        $tips = Tips::where('corpid', $this->corpid)->with(["Achievement"=>function($query)use($ac_id){

            $query->where('user_id', $ac_id);
        }])->get();
        $tisNum = [];
        $tisName = [];
        $tisCol = [];
        foreach ($tips as $k => $tip) {
            $standard = 0;
            $score = 0;
            //  dd($tip->Achievement);
            foreach ($tip->Achievement as $k2 => $tip2) {
                $standard += $tip2->standard;
                $score += $tip2->score;
            }
            if ($score == 0) {
                $tisNum[$k] = 0;
            } else {
                $tisNum[$k] = intval($score / $standard * 100);
            }
            $tisName[$k] = substr($tip->name , 0 , 18);
            $tisCol[$k]= $tip->color;

        }

        return view($view)
            //->with('months',$month_array)
            ->with('months',$jixiao)
            ->with('value_opinion',$return_op_v)
            ->with('name_opinion',$return_op_n)
            ->with('is_origin',$is_origin)
            ->with('perf',$perf)
            ->with('uid',$uid)
            ->with('tisNum', json_encode($tisNum))
            ->with('tisCol', json_encode($tisCol))
            ->with('tisName', json_encode($tisName));
    }


    //查看全员考评
    public function getAllPerf(Request $request)
    {
        $year_param = $request->input('year', 0);
        $company = Company::where('id',$this->corpid)->first();
        if(!is_positive_int($year_param)){
            $year_param = getCurrentYear();
        }
        if(!in_array($year_param,explode(',',$company->years_array))){
            $year_param = $company->from_year;
        }
        return redirect('/user/performance/all-perf?year='.$year_param);


        $uu = User::where('corpid',$this->corpid)->where('status','1')->get();
        if(count($uu) > 0){
            foreach ($uu as $u){
                $cu_perf = UserPerformance::where('user_id',$u->id)->where('corpid',$this->corpid)->first();
                if(!empty($cu_perf)){
                    $standard_t = Achievement::where('corpid',$this->corpid)->where('user_id',$u->id)->sum('standard');
                    $score_t = Achievement::where('corpid',$this->corpid)->where('user_id',$u->id)->sum('score');
                    if($standard_t == 0){
                        $gg = 0;
                    }else{
                        $gg =  round($score_t/$standard_t,2)*100;
                        $gg = intval($gg);
                    }

                    $kq_score = Attendance::where('corpid',$this->corpid)->where('user_id',$u->id)->sum('score');

                    $reward = RewardPunishDetail::where('corpid',$this->corpid)->where('to_user_id',$u->id)->where('is_effective','1')->where('kind','1')->sum('score');
                    $punish = RewardPunishDetail::where('corpid',$this->corpid)->where('to_user_id',$u->id)->where('is_effective','1')->where('kind','2')->sum('score');
                    $cu_perf->jiangcheng = $reward + $punish;
                    $cu_perf->kaoqin = $kq_score;
                    $cu_perf->yeji = $gg;
                    $cu_perf->total = $gg + $kq_score+ $reward + $punish;
                    $cu_perf->save();
                }

            }
        }

        $groups = Group::where('corpid',$this->corpid)->get();
        foreach ($groups as $gt){
            $gt->users = User::where('group_id',$gt->id)->where('status','1')->get();
        }
        $g_collect = collect();
        foreach ($groups as $g){
            if($g->fid == 0){
                $g_collect[] = $g;
                foreach ($groups as $gg){
                    if($gg->fid == $g->id){
                        $g_collect[] = $gg;
                        foreach ($groups as $ggg){
                            if($ggg->fid == $gg->id){
                                $g_collect[] = $ggg;
                            }
                        }
                    }
                }
            }
        }
        //$perf = UserPerformance::where('corpid',$this->corpid)->get();
        $view = 'sysadmin.kaohe.all-evaluation';
        return view($view)
            ->with('year_param', $year_param)
            ->with('perf',$g_collect);
    }


    //非企业微信功能//
    //申请加入的列表
    public function getApplylist(Request $request)
    {
        $name = $request->input('name','');
        if(empty($name)){
            $list = RegUser::where('corpid',$this->corpid)->where('status','3')->get();
        }else{
            $list = RegUser::where('corpid',$this->corpid)->where('status','3')->get();
        }
        if(is_mobile()){
            $view = 'sysadmin.colleague-verifice';
        }else{
            $view = 'pc_sysadmin.colleague-verifice';
        }
        
        return view($view)
            ->with('list',$list);
    }


    //处理申请1-同意，2-不同意
    public function postApply(Request $request)
    {
        $result = array(
            'status'        => 'fail',
            'msg'           => '处理失败',
            'data'          => '',
            'redirectUrl'   => ''
        );
        $aid = $request->input('applyid',0);
        $is_agree = $request->input('is_agree',2);
        if($aid <= 0){
            $result['msg'] = 'id不正确';
            return Response::json($result);
        }
        $reguser = RegUser::find($aid);
        if(empty($reguser)){
            $result['msg'] = '该申请不存在';
            return Response::json($result);
        }
        $second_user = User::find($reguser->user_id);
        if($is_agree == 1){
            $reguser->status = 1;
            $reguser->save();


            $second_user->status = 1;
            $second_user->save();

            $jixiao = UserPerformance::where('corpid',$reguser->corpid)->where('user_id',$second_user->id)->first();
            if(empty($jixiao)){
                //新建默认绩效记录
                $perf = new UserPerformance();
                $perf->user_id = $second_user->id;
                $perf->corpid = $reguser->corpid;
                $perf->save();
            }

        }else{
            $reguser->status = 4;//拒绝
            $reguser->save();

            $second_user->status = 4;
            $second_user->save();
        }
        $result['status'] = 'success';
        $result['msg'] = '成功';
        $result['redirectUrl'] = '/sysadmin/user/applylist';
        return Response::json($result);
    }


    //让用户退出企业
    public function postQuitCompany(Request $request)
    {
        $result = array(
            'status'        => 'fail',
            'msg'           => '处理失败',
            'data'          => '',
            'redirectUrl'   => ''
        );
        $uid = $request->input('userid',0);
        if($uid <= 0){
            $result['msg'] = 'id不正确';
            return Response::json($result);
        }
        $reguser = RegUser::where('corpid',$this->corpid)->where('user_id',$uid)->first();
        if(empty($reguser)){
            $result['msg'] = '该用户不存在';
            return Response::json($result);
        }
        $reguser->status = 4;
        $reguser->save();

        $user = User::find($uid);
        $user->status = 4;
        $user->save();

        $result['status'] = 'success';
        $result['msg'] = '成功';
        return Response::json($result);
    }


    public function getExportExcel(Request $request){
        $depart = Group::where('corpid',$this->corpid)->select('id','group_name as value')->get();
        foreach ($depart as $d)
        {
            $d->childs =  User::where('corpid',$this->corpid)->where('group_id',$d->id)->select('id','qw_name as value')->get();
        }
        $depart = $depart->toJson();
        
        return view('pc_sysadmin.data-out')->with('dep',$depart);
    }


    //用户考核导出
    public function getExportThexcel(Request $request)
    {
        $data = Input::only('startDate','endDate');
        $groupid = $request->input('groupid',-1);
        $uids = $request->input('uids',-1);
        $items = $request->input('items',0);
        $items = json_decode($items);

        if($groupid == -1){
            $uid = User::where('corpid',$this->corpid)->lists('id');
        }else{
            $uid = array();
            $uid[] =  $uids;
        }
        //dd($uids,$items);

        $array = array();//结果
        foreach($uid as $u)
        {
            $array[$u]['zongfen'] = 0;
            $array[$u]['name'] = getUserName($u);
            if(in_array(1,$items)){
                $array[$u]['jiangcheng']    =  RewardPunishDetail::where('corpid',$this->corpid)->where('to_user_id',$u)->where('is_effective','1')
                    ->where('created_at','>=',$data['startDate'])->where('created_at','<=',$data['endDate'])->sum('score');
                $array[$u]['zongfen'] += $array[$u]['jiangcheng'];
            }
            if(in_array(2,$items)){
                $start = strtotime($data['startDate']);
                $end = strtotime($data['endDate']);
                //dd($start,$end);
                $array[$u]['kaoqin']    =  Attendance::where('corpid',$this->corpid)->where('user_id',$u)
                    ->where('time','>=',$start)->where('time','<=',$end)->sum('score');
                $array[$u]['zongfen'] += $array[$u]['kaoqin'];
            }
            if(in_array(3,$items)){
                $array[$u]['yeji']    =  Achievement::where('corpid',$this->corpid)->where('user_id',$u)
                    ->where('created_at','>=',$data['startDate'])->where('created_at','<=',$data['endDate'])->sum('score');
                $array[$u]['zongfen'] += $array[$u]['yeji'];
            }

        }
        //dd($array);
        $i = 0;

        header('Content-Type: text/xls');
        header("Content-type:application/vnd.ms-excel;charset=utf-8");
        header("Content-Disposition: attachment; filename=".'detail'. date("YmdHis", time()) . ".xls");
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
        header('Expires:0');
        header("Pragma: no-cache");
        try{
            //导出数据
            echo chr(239) . chr(187) . chr(191) .'<table border=1>';
            echo '<tr>';
            echo '<th>NO</th>';
            echo '<th>姓名</th>';
            echo '<th>时间</th>';
            if(in_array(1,$items)){
                echo '<th>奖惩</th>';
            }
            if(in_array(2,$items)){
                echo '<th>考勤</th>';
            }
            if(in_array(3,$items)){
                echo '<th>业绩</th>';
            }
            echo '<th>总分 </th>';
            echo '</tr>';
            foreach ($array as $v) {
                echo '<tr>';
                echo '<td>'.($i+1).'</td>';
                echo '<td>'.$v['name'].'</td>';
                echo '<td>'.$data['startDate'].'-'.$data['endDate'].'</td>';
                if(in_array(1,$items)){
                    echo '<td>'.$v['jiangcheng'].'</td>';
                }
                if(in_array(2,$items)){
                    echo '<td>'.$v['kaoqin'].'</td>';
                }
                if(in_array(3,$items)){
                    echo '<td>'.$v['yeji'].'</td>';
                }
                echo '<td>'.$v['zongfen'].'</td>';
                echo '</tr>';
            }
            echo '</table>';
        }catch (\Exception $e){
            dd($e->getMessage());
        }
    }
   
}


